import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/device_detail_controller.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../services/theme_service.dart';
import '../../../translations/app_translations.dart';

class DeviceDetailView extends GetView<DeviceDetailController> {
  const DeviceDetailView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    final themeService = Get.find<ThemeService>();
    
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.deviceDetail.tr),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: controller.refreshDeviceDetail,
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        
        if (controller.errorMessage.value != null) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  controller.errorMessage.value ?? '发生未知错误',
                  style: TextStyle(color: extension?.errorText),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: controller.refreshDeviceDetail,
                  child: Text(LocaleKeys.retry.tr),
                ),
              ],
            ),
          );
        }
        
        final device = controller.device.value;
        if (device == null) {
          return Center(
            child: Text(
              LocaleKeys.deviceNotFound.tr,
              style: TextStyle(color: extension?.errorText),
            ),
          );
        }
        
        final product = controller.product.value;
        
        return RefreshIndicator(
          onRefresh: controller.refreshDeviceDetail,
          child: ListView(
            padding: const EdgeInsets.all(16),
            children: [
              // 设备基本信息卡片
              _buildCard(
                context,
                title: LocaleKeys.basicInfo.tr,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildInfoItem(context, LocaleKeys.deviceName.tr, device.deviceName),
                    _buildInfoItem(context, LocaleKeys.serialNumber.tr, device.deviceSn),
                    _buildInfoItem(context, LocaleKeys.status.tr, _buildStatusBadge(device.status)),
                    _buildInfoItem(context, LocaleKeys.createTime.tr, controller.formatDateTime(device.createTime)),
                    if (device.lastOnlineTime != null)
                      _buildInfoItem(context, LocaleKeys.lastOnlineTime.tr, controller.formatDateTime(device.lastOnlineTime)),
                    if (device.lastOfflineTime != null)
                      _buildInfoItem(context, LocaleKeys.lastOfflineTime.tr, controller.formatDateTime(device.lastOfflineTime)),
                  ],
                ),
              ),
              
              const SizedBox(height: 16),
              
              // 产品信息卡片
              _buildCard(
                context,
                title: LocaleKeys.productInfo.tr,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildInfoItem(context, LocaleKeys.productName.tr, product?.productName ?? device.productName ?? LocaleKeys.unknown.tr),
                    _buildInfoItem(context, LocaleKeys.productKey.tr, product?.productKey ?? device.productKey ?? LocaleKeys.unknown.tr),
                    if (product != null) ...[
                      _buildInfoItem(context, LocaleKeys.nodeType.tr, controller.getNodeTypeDesc(product.nodeType)),
                      _buildInfoItem(context, LocaleKeys.protocol.tr, controller.getProtocolTypeDesc(product.protocolType)),
                      _buildInfoItem(context, LocaleKeys.dataFormat.tr, controller.getDataFormatDesc(product.dataFormat)),
                      _buildInfoItem(context, LocaleKeys.authType.tr, controller.getAuthTypeDesc(product.authenticationType)),
                      if (product.description.isNotEmpty)
                        _buildInfoItem(context, LocaleKeys.productDesc.tr, product.description),
                    ],
                  ],
                ),
              ),
              
              const SizedBox(height: 16),
              
              // 设备详细参数卡片
              _buildCard(
                context,
                title: LocaleKeys.deviceParams.tr,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildInfoItem(context, LocaleKeys.deviceId.tr, '${device.deviceId}'),
                    _buildInfoItem(context, LocaleKeys.firmwareVersion.tr, device.firmwareVersion),
                    _buildInfoItem(context, LocaleKeys.ipAddress.tr, device.ipAddress),
                    _buildInfoItem(context, LocaleKeys.tenantId.tr, device.tenantId),
                  ],
                ),
              ),
              
              const SizedBox(height: 16),
              
              // 设备位置信息卡片（如果有位置信息）
              if (device.latitude != null && device.longitude != null)
                _buildCard(
                  context,
                  title: LocaleKeys.locationInfo.tr,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildInfoItem(context, LocaleKeys.longitude.tr, '${device.longitude}'),
                      _buildInfoItem(context, LocaleKeys.latitude.tr, '${device.latitude}'),
                    ],
                  ),
                ),
                
              // 标签信息卡片（如果有标签信息）
              if (device.tags != '{}')
                _buildCard(
                  context,
                  title: LocaleKeys.tagsInfo.tr,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: Text(
                      device.tags,
                      style: theme.textTheme.bodyMedium,
                    ),
                  ),
                ),
            ],
          ),
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 跳转到设备控制页面
          // Get.toNamed('/device-control', arguments: {'deviceId': controller.deviceId});
        },
        tooltip: LocaleKeys.deviceControl.tr,
        child: const Icon(Icons.settings_remote),
      ),
    );
  }
  
  Widget _buildCard(BuildContext context, {required String title, required Widget child}) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(extension?.cardRadius ?? 8),
        side: BorderSide(color: extension?.cardBorder ?? Colors.grey.shade200),
      ),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: Text(
                title,
                style: theme.textTheme.titleMedium?.copyWith(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Divider(color: extension?.divider),
            const SizedBox(height: 8),
            child,
          ],
        ),
      ),
    );
  }
  
  Widget _buildInfoItem(BuildContext context, String label, dynamic value) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              label,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: extension?.textSecondary,
              ),
            ),
          ),
          Expanded(
            child: value is Widget ? value : Text(
              value.toString(),
              style: theme.textTheme.bodyMedium,
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildStatusBadge(int status) {
    final theme = Get.theme;
    final extension = theme.extension<AppThemeExtension>();
    
    String label;
    Color color;
    Color textColor = Colors.white;
    IconData iconData;
    
    switch (status) {
      case 0: // 未激活
        label = LocaleKeys.deviceInactive.tr;
        color = extension?.disabledBg ?? Colors.grey.shade200;
        textColor = extension?.disabledText ?? Colors.grey;
        iconData = Icons.device_unknown;
        break;
      case 1: // 在线
        label = LocaleKeys.deviceOnline.tr;
        color = extension?.successBg ?? Colors.green.shade100;
        textColor = extension?.successText ?? Colors.green;
        iconData = Icons.check_circle_outline;
        break;
      case 2: // 离线
        label = LocaleKeys.deviceOffline.tr;
        color = extension?.warningBg ?? Colors.orange.shade100;
        textColor = extension?.warningText ?? Colors.orange;
        iconData = Icons.offline_bolt;
        break;
      case 3: // 禁用
        label = LocaleKeys.deviceDisabled.tr;
        color = extension?.errorBg ?? Colors.red.shade100;
        textColor = extension?.errorText ?? Colors.red;
        iconData = Icons.block;
        break;
      default:
        label = LocaleKeys.statusUnknown.tr;
        color = extension?.disabledBg ?? Colors.grey.shade200;
        textColor = extension?.disabledText ?? Colors.grey;
        iconData = Icons.device_unknown;
    }
    
    // 使用与设备列表页相同的徽章样式，并确保不可点击
    return IgnorePointer(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Text(
          label, 
          style: TextStyle(
            color: textColor, 
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
} 